﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using RBAC_Uthorization.API.Application.Command.RoleMenuCommand;
using RBAC_Uthorization.API.DTO;
using RBAC_Uthorization.API.Extensions;
using RBAC_Uthorization.Domain;
using RBAC_Uthorization.Domain.Entity;
using RBAC_Uthorization.Infrstructre.Impl;
using RBAC_Uthorization.Infrstructre.Interface;
using StackExchange.Redis;

namespace RBAC_Uthorization.API.Application.CommandHandlers.RoleMenuHandler
{
    public class RoleMenuCreateCommandHandlers : IRequestHandler<RoleMenuCreateCommand, ApiResult<int>>
    {
        private readonly ILogger<RoleMenuCreateCommandHandlers> _logger;
        private readonly IRoleMenuFuncRepository _roleMenuFuncRepository;
        private readonly IMapper _mapper;
        private readonly IRoleMenuRepository _roleMenuRepository;
        private readonly IUserRoleRepository _userRoleRepository;
        private readonly IConfiguration _configuration;
        private readonly RedisConnectionService _redisConnectionService;


        public RoleMenuCreateCommandHandlers(ILogger<RoleMenuCreateCommandHandlers> logger, IMapper mapper, IRoleMenuRepository roleMenuRepository, IRoleMenuFuncRepository roleMenuFuncRepository, IUserRoleRepository userRoleRepository, IConfiguration configuration, RedisConnectionService redisConnectionService)
        {
            _logger = logger;
            _mapper = mapper;
            _roleMenuRepository = roleMenuRepository;
            _roleMenuFuncRepository = roleMenuFuncRepository;
            _userRoleRepository = userRoleRepository;
            _configuration = configuration;
            _redisConnectionService = redisConnectionService;
        }


        public async Task<ApiResult<int>> Handle(RoleMenuCreateCommand request, CancellationToken cancellationToken)
        {
           
            if (_configuration["Redis:Redisif"] == "1")
            {
              
                foreach (var item in await _userRoleRepository.GetAllAsunc(x => x.role_id == request.dto.RoleId && x.del_flag == 0))
                {
                    // 删除 Redis 中的菜单
                    await _redisConnectionService.DeleteAsync($"user:{item.user_id}:{request.sys_id}:menuIds");

                }
            }
            // 开启事务
            await _roleMenuRepository.BeginTransactionAsync();
            try
            {

                // 删除现有的角色菜单
                var existingRoleMenus = await _roleMenuRepository.GetAllAsunc(x => x.role_id == request.dto.RoleId);
                foreach (var roleMenu in existingRoleMenus)
                {
                    await _roleMenuRepository.DeleteAsync(roleMenu.id);
                }

                var existingRoleMenuFuncs = await _roleMenuFuncRepository.GetAllAsunc(x => x.role_id == request.dto.RoleId);
                foreach (var roleMenuFunc in existingRoleMenuFuncs)
                {

                    await _roleMenuFuncRepository.DeleteAsync(roleMenuFunc.id);
                }

                // 添加新的角色菜单
                foreach (var menuId in request.dto.MenuId)
                {
                    if (menuId.Contains("-"))
                    {
                        var menuIdArray = menuId.Split("-");
                        var roleMenuFunc = new sys_role_menu_fun
                        {
                            role_id = request.dto.RoleId,
                            menu_id = Convert.ToInt32(menuIdArray[0]),
                            fun_id = Convert.ToInt32(menuIdArray[1]),
                            create_by = request.CreateName
                        };
                        await _roleMenuFuncRepository.AddAsync(roleMenuFunc);
                    }
                    else
                    {
                        var roleMenu = new sys_role_menu
                        {
                            role_id = request.dto.RoleId,
                            menu_id = Convert.ToInt32(menuId),
                            create_by = request.CreateName
                        };
                        await _roleMenuRepository.AddAsync(roleMenu);
                    }
                }

                await _roleMenuRepository.CommitTransactionAsync(); // 提交事务

                _logger.LogInformation($"创建人:{request.CreateName}角色菜单功能{request.dto}");
                return new ApiResult<int> { Code = ResultCode.Ok, Message = "角色菜单创建成功" };
            }
            catch (Exception ex)
            {
                await _roleMenuRepository.RollbackTransactionAsync(); // 回滚事务
                _logger.LogError(ex, "创建角色菜单失败");
                return new ApiResult<int> { Code = ResultCode.Fail, Message = "创建角色菜单失败" };
            }
        }
    }
}
